package com.ecnu.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ecnu.common.constant.HttpStatus;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.entity.SysDictData;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.exception.ServiceException;
import com.ecnu.common.utils.DateUtils;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.http.UrlUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.*;
import com.ecnu.system.domain.dto.ProjectIndexFileDTO;
import com.ecnu.system.domain.dto.SearchConditionDto;
import com.ecnu.system.domain.dto.incubation.FactoryPageDTO;
import com.ecnu.system.domain.dto.incubation.IncubationFactoryDTO;
import com.ecnu.system.domain.dto.incubation.IncubationFileDTO;
import com.ecnu.system.domain.dto.incubation.TransferDTO;
import com.ecnu.system.domain.vo.Incubation.FactoryPageVO;
import com.ecnu.system.domain.vo.Incubation.IncubationFactoryVO;
import com.ecnu.system.domain.vo.MapVO;
import com.ecnu.system.mapper.*;
import com.ecnu.system.service.IIncubationFactoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.rtf.RTFEditorKit;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.ecnu.system.domain.menu.OtherMenu.*;

/**
 * <p>
 * ecnu_二期_成果车间 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-10-16
 */
@Service
public class IncubationFactoryServiceImpl
        extends ServiceImpl<IncubationFactoryMapper, IncubationFactory>
        implements IIncubationFactoryService {
    @Autowired
    private IncubationFactoryMapper incubationFactoryMapper;
    @Autowired
    private IncubationFileMapper incubationFileMapper;
    @Autowired
    private IncubationProjectMapper incubationProjectMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectServiceImpl projectService;
    @Autowired
    private ProjectFileServiceImpl projectFileService;
    @Autowired
    private IncubationFileServiceImpl incubationFileService;
    @Autowired
    private SysDictDataMapper dictDataMapper;


    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }

    @Override
    public AjaxResult edit(IncubationFactoryDTO dto, LoginUser loginUser) {
        if (StringUtils.isNotBlank(dto.getId())) {
            LambdaQueryWrapper<IncubationFactory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(IncubationFactory::getId, dto.getId());
            wrapper.eq(IncubationFactory::getDelFlag, "0");
            IncubationFactory factory = incubationFactoryMapper.selectOne(wrapper);
            if (factory == null) {
                return AjaxResult.error(HttpStatus.MOVED_PERM, "成果不存在，请刷新页面");
            }
        }
        IncubationFactory incubationFactory = new IncubationFactory();
        BeanUtils.copyProperties(dto, incubationFactory);
//        incubationFactory.setCreateUser(String.valueOf(loginUser.getUserId()));
        String editStatus = dataEdit(incubationFactory, String.valueOf(loginUser.getUserId()));
        if (editStatus.equals("")) {
            return AjaxResult.error(HttpStatus.NOT_MODIFIED, "成果参数填写错误，请检查");
        }
        dto.setId(editStatus);
        Boolean fileStatus = fileEdit(dto, loginUser);
        if (!fileStatus) {
            return AjaxResult.error(HttpStatus.NOT_MODIFIED, "成果文件上传，请检查");
        }
        return AjaxResult.success("保存成功");
    }

    @Override
    public AjaxResult infoById(String id) {
        //查询成果
        IncubationFactory incubationFactory = incubationFactoryMapper.selectOne(
                new LambdaQueryWrapper<IncubationFactory>()
                        .eq(IncubationFactory::getId, id)
                        .eq(IncubationFactory::getDelFlag, "0"));
        if (incubationFactory == null) {
            return AjaxResult.error(HttpStatus.MOVED_PERM, "成果不存在，请刷新页面");
        }
        IncubationFactoryVO vo = new IncubationFactoryVO();
        BeanUtils.copyProperties(incubationFactory, vo);

        ArrayList<String> strings = new ArrayList<>();
        strings.add(id);
        //查询文件
        Map<String, List<IncubationFile>> stringListMap = infoFileList(strings);
        List<IncubationFile> incubationFiles = stringListMap.get(id);
        if (incubationFiles == null) {
            return AjaxResult.success(vo);
        }
        //按照文件类型进行分组
        Map<String, List<IncubationFile>> collect = incubationFiles.stream()
                .collect(Collectors.groupingBy(IncubationFile::getFileType));
        collect.forEach((key, value) -> {
            switch (key) {
                case 文献:
                    List<ProjectIndexFileDTO> literatureFiles = fileToVo(value);
                    vo.setLiteratureFiles(literatureFiles);
                    break;
                case 数据:
                    List<ProjectIndexFileDTO> dataFiles = fileToVo(value);
                    vo.setDataFiles(dataFiles);
                    break;
                case 代码:
                    List<ProjectIndexFileDTO> codeFiles = fileToVo(value);
                    vo.setCodeFiles(codeFiles);
                    break;
                case 其他:
                    List<ProjectIndexFileDTO> otherFiles = fileToVo(value);
                    vo.setOtherFiles(otherFiles);
                    break;
            }
        });

        return AjaxResult.success(vo);
    }

    @Override
    public Boolean fileToSave(IncubationFileDTO dto, LoginUser loginUser) {
        IncubationFactoryDTO incubationFactoryDTO = new IncubationFactoryDTO();
        ArrayList<IncubationFileDTO> dtos = new ArrayList<>();
        dtos.add(dto);
        incubationFactoryDTO.setFileList(dtos);
        return fileEdit(incubationFactoryDTO, loginUser);
    }

    @Override
    public TableDataInfo listForIncubation(FactoryPageDTO dto, LoginUser proUser) {
        //  todo 还没对的，记得需要看下怎么做权限
        boolean isUnauthorizedRole = proUser.getUser().getRoles().stream()
                .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId() != 2L);

        //成果搜索
        List<FactoryPageVO> factories = IncubationSearch(dto);
        LinkedList<Map<String, Object>> maps = new LinkedList<>();
//        结构整理
        factories.forEach(factory -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", factory.getId());
            map.put("name", factory.getName());//成果名称
            map.put("author", factory.getAuthor());//成果作者
            map.put("createUser", factory.getUserName());//成果上传人
            map.put("createTime", DateUtils.dateToString(factory.getCreateTime(), DateUtils.点号));//成果上传时间
            map.put("isAdmin", String.valueOf(proUser.getUserId()).equals(factory.getCreateUser())
                    || isUnauthorizedRole ? true : false);//是否是管理员，不是的话就只能显示自己的调整
            maps.add(map);

        });
        return OtherUtil.tableSuccess2(maps, new PageInfo(factories).getTotal());
    }

    @Override
    public TableDataInfo listForAnalysis(FactoryPageDTO dto, LoginUser proUser) {
        //  todo 还没对的，记得需要看下怎么做权限
        boolean isUnauthorizedRole = proUser.getUser().getRoles().stream()
                .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId() != 2L);

        //成果搜索
        List<FactoryPageVO> factories = IncubationSearch(dto);
        LinkedList<Map<String, Object>> maps = new LinkedList<>();
//        结构整理
        factories.forEach(factory -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", factory.getId());
            map.put("name", factory.getName());//成果名称
            map.put("author", factory.getAuthor());//成果作者
            map.put("source", factory.getSource());//成果来源
            switch (factory.getEvaluateStatus()) {
                case "0":
                    map.put("evalStatusName", "未评估");
                    break;
                case "1":
                    map.put("evalStatusName", "评估中");
                    break;
                case "2":
                    map.put("evalStatusName", "已通过");
                    break;
                case "-1":
                    map.put("evalStatusName", "未通过");
                    break;
                default:
                    map.put("evalStatusName", "未知");
                    break;
            }//评估状态
            map.put("evaluateTitle", factory.getEvaluateTitle());//评估详情
            map.put("convertRate", factory.getConvertRate());//实验化潜力
            map.put("analysisStatus", factory.getAnalysisStatus());//解析状态
            map.put("isAdmin", String.valueOf(proUser.getUserId()).equals(factory.getCreateUser())
                    || isUnauthorizedRole ? true : false);//是否是管理员，不是的话就只能显示自己的调整
            maps.add(map);

        });
        return OtherUtil.tableSuccess2(maps, new PageInfo(factories).getTotal());
    }

    @Override
    public TableDataInfo listByClaim(FactoryPageDTO dto, LoginUser proUser) {
        //随机获取3条数据/相关推荐数据（相关的话按照参与成果的关键词进行筛选）
        LinkedList<Map<String, Object>> maps = new LinkedList<>();
        ArrayList<String> list = new ArrayList<>();
        if (dto.getPageDomain().getPageNum().equals(1)) {
            //写入第一页只7条数据
            PageDomain pageDomain = dto.getPageDomain();
            BeanUtils.copyProperties(dto.getPageDomain(), pageDomain);
            pageDomain.setPageSize(pageDomain.getPageSize() - 3);
            dto.setPageDomain(pageDomain);
            List<FactoryPageVO> factoryPageVOS = otherForClaim(dto, proUser);
            factoryPageVOS.forEach(factory -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", factory.getId());
                map.put("name", factory.getName());//成果名称
                map.put("author", factory.getAuthor());//成果作者
                map.put("createUser", factory.getUserName());//成果上传人
                map.put("createTime", factory.getCreateTime());//成果上传时间
                map.put("source", factory.getSource());//成果来源
                map.put("isClaim", false);
                maps.add(map);
                list.add(factory.getId());
            });
        }
        //列表数据
        List<FactoryPageVO> factories = IncubationClaimList(dto, list, proUser);
//        结构整理
        factories.forEach(factory -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", factory.getId());
            map.put("name", factory.getName());//成果名称
            map.put("author", factory.getAuthor());//成果作者
            map.put("createUser", factory.getUserName());//成果上传人
            map.put("createTime", factory.getCreateTime());//成果上传时间
            map.put("source", factory.getSource());//成果来源
            map.put("isClaim", (StringUtils.isBlank(factory.getProjectUser()) || !factory.getProjectUser().equals(proUser.getUserId().toString())) ? false : true);//成果认领状态
            maps.add(map);
        });
        return OtherUtil.tableSuccess2(maps, new PageInfo(factories).getTotal());
    }

    @Override
    public TableDataInfo claimList(FactoryPageDTO dto, LoginUser proUser) {
        try {
            //随机获取3条数据/相关推荐数据（相关的话按照参与成果的关键词进行筛选）
            LinkedList<Map<String, Object>> maps = new LinkedList<>();
            ArrayList<String> list = new ArrayList<>();

            // 判断是否是第一页
            boolean isFirstPage = dto.getPageDomain().getPageNum() == 1;
            int originalPageSize = dto.getPageDomain().getPageSize();
            int recommendCount = isFirstPage ? 3 : 0; // 第一页推荐3条

            if (isFirstPage) {
                //写入第一页只7条数据
                PageDomain pageDomain = dto.getPageDomain();
                BeanUtils.copyProperties(dto.getPageDomain(), pageDomain);
                pageDomain.setPageSize(pageDomain.getPageSize() - recommendCount);
                dto.setPageDomain(pageDomain);
                List<FactoryPageVO> factoryPageVOS = otherForClaim(dto, proUser);
                factoryPageVOS.forEach(factory -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", factory.getId());
                    map.put("name", factory.getName());//成果名称
                    map.put("author", factory.getAuthor());//成果作者
                    map.put("createUser", factory.getUserName());//成果上传人
                    map.put("createTime", factory.getCreateTime());//成果上传时间
                    map.put("source", factory.getSource());//成果来源
                    map.put("evaluateTitle", factory.getEvaluateTitle());//评估详情
                    String personnel = factory.getPersonnel();
                    String userId = proUser != null && proUser.getUserId() != null ? proUser.getUserId().toString() : null;
                    boolean isClaim = false;

                    if (StringUtils.isNotBlank(personnel) && userId != null) {
                        Set<String> personnelSet = new HashSet<>(Arrays.asList(personnel.split(",")));
                        isClaim = personnelSet.contains(userId);
                    }
                    map.put("isClaim", isClaim);//成果认领状态
                    map.put("isRecom", true);//推荐状态
                    maps.add(map);
                    list.add(factory.getId());
                });
            }
            //列表数据
            List<FactoryPageVO> factories = IncubationClaimList(dto, list, proUser);
//        结构整理
            factories.stream()
                    .filter(factory -> !list.contains(factory.getId()))
                    .forEach(factory -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", factory.getId());
                        map.put("name", factory.getName());//成果名称
                        map.put("author", factory.getAuthor());//成果作者
                        map.put("createUser", factory.getUserName());//成果上传人
                        map.put("createTime", factory.getCreateTime());//成果上传时间
                        map.put("source", factory.getSource());//成果来源
                        /**认领状态**/
                        String personnel = factory.getPersonnel();
                        String userId = proUser != null && proUser.getUserId() != null ? proUser.getUserId().toString() : null;
                        boolean isClaim = false;

                        if (StringUtils.isNotBlank(personnel) && userId != null) {
                            Set<String> personnelSet = new HashSet<>(Arrays.asList(personnel.split(",")));
                            isClaim = personnelSet.contains(userId);
                        }
                        /**********/
                        map.put("isClaim", isClaim);//成果认领状态
                        map.put("evaluateTitle", factory.getEvaluateTitle());//评估详情
                        map.put("isRecom", false);//推荐状态
                        maps.add(map);

                    });
            return OtherUtil.tableSuccess2(maps, new PageInfo(factories).getTotal()+recommendCount);
        } catch (Exception e) {
            log.error("###认领列表处理失败" + e.getMessage());
            return OtherUtil.tableError("认领列表处理失败");
        }
    }

    @Override
    public AjaxResult claimEdit(IncubationFactoryDTO dto, LoginUser loginUser) {
        //先查看当前成果是否存在 incubation_factory
        LambdaQueryWrapper<IncubationFactory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IncubationFactory::getId, dto.getId());
        wrapper.eq(IncubationFactory::getDelFlag, 0);//未删除
        wrapper.eq(IncubationFactory::getEvaluateStatus, 2);//已通过
        IncubationFactory incubationFactory = incubationFactoryMapper.selectOne(wrapper);
        if (incubationFactory == null) {
            return AjaxResult.error("认领失败，请检查该成果是否已删除或未完成评估");
        }
        try {
            //看成果认领情况
            String personnel = incubationFactory.getPersonnel();
//            boolean notBlank = StringUtils.isNotBlank(personnel);
            List<String> list = StringUtils.isNotBlank(personnel) ?
                    new ArrayList<>(Arrays.asList(personnel.split(","))) :
                    new ArrayList<>();
            if (StringUtils.isNotEmpty(list)) {
//                List<String> personnelList = Arrays.asList(personnel.split(","));

                if (list.contains(loginUser.getUserId().toString())) {
                    return AjaxResult.error("认领失败，请勿重复认领");
                }
                if (list.stream().count() >= incubationFactory.getPersonNum()) {
                    return AjaxResult.error("认领失败，该成果已满设定认领人数");
                }
            }
//            List<String> list = StringUtils.isNotBlank(personnel) ?
//                    new ArrayList<>(Arrays.asList(personnel.split(","))) :
//                    new ArrayList<>();
            //认领 incubation_project-->project
            LambdaQueryWrapper<IncubationProject> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(IncubationProject::getIncuId, dto.getId());
            queryWrapper.eq(IncubationProject::getDelFlag, 0);
            IncubationProject incubationProject = incubationProjectMapper.selectOne(queryWrapper);
            if (incubationProject == null) {
                return AjaxResult.error("认领失败，未查询到成果解析数据，请联系管理员处理");
            }
            Project project = new Project();
            BeanUtils.copyProperties(incubationProject, project);
            project.setId(getId());
            project.setRangeType(loginUser.getUserId().toString());
            project.setCreateUser(loginUser.getUserId().toString());
            int insert = projectMapper.insert(project);
            if (insert == 0) {
                log.error("认领失败，成果id【" + incubationFactory.getId() + "】,认领人id【" + loginUser.getUserId() + "】");
                return AjaxResult.error("认领失败，请检查该成果是否已删除或未完成评估，如再出现请联系管理员处理");
            }

            //写入incubationFactory表
            StringBuilder sb = new StringBuilder();
            list.add(loginUser.getUserId().toString());//添加认领人
            incubationFactory.setPersonnel(String.join(",", list));//添加认领人转成字符串
//            incubationFactory.setPersonnel(sb.toString());
            int i = incubationFactoryMapper.updateById(incubationFactory);
            //写入project相关文件表
            List<IncubationFile> incubationFiles = incubationFileMapper.selectList(
                    new LambdaQueryWrapper<IncubationFile>()
                            .eq(IncubationFile::getIncuId, incubationFactory.getId())
                            .eq(IncubationFile::getDelFlag, 0));
            if (StringUtils.isNotEmpty(incubationFiles)) {
                incubationFiles.forEach(file -> {
                    file.setIncuId(project.getId());
                    file.setId(getId());
                });
                List<ProjectFile> copy = OtherUtil.copy(incubationFiles, ProjectFile.class);
                projectFileService.saveBatch(copy);
            }

            return AjaxResult.success("认领成功");
        } catch (Exception e) {
            log.error("###成果：" + incubationFactory.getName() + ",对用户：" + loginUser.getUsername()
                    + "认领失败，原因：" + e.getMessage());
            return AjaxResult.error("认领失败，请联系管理员解决");
        }
    }

    @Override
    public AjaxResult claimDel(String id, LoginUser loginUser) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getId, id)
                .eq(Project::getDelFlag, 0);
        boolean isUnauthorizedRole = loginUser.getUser().getRoles().stream()
                .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId() != 2L);
        //判断权限，仅管理员和机构管理员可以直接取消
        if (!isUnauthorizedRole) {
            queryWrapper.eq(Project::getCreateUser, loginUser.getUserId().toString());
        }
        //找出认领的成果
        Project project = projectMapper.selectOne(queryWrapper);
        if (project == null) {
            return AjaxResult.error("取消失败，请检查该成果是否认领");
        }
        if (isUnauthorizedRole) {
            queryWrapper.eq(Project::getCreateUser, project.getCreateUser());
            loginUser.setUserId(Long.valueOf(project.getCreateUser()));
        }
        project.setDelFlag("2");
        int update = projectMapper.update(project, queryWrapper);

        //先查看当前成果是否存在 incubation_factory
        LambdaQueryWrapper<IncubationFactory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IncubationFactory::getId, project.getIncuId())
                .eq(IncubationFactory::getEvaluateStatus, 2);//已通过
        IncubationFactory incubationFactory = incubationFactoryMapper.selectOne(wrapper);
        if (incubationFactory == null) {
            return AjaxResult.success("取消成功");
        }
        //看成果认领情况
        String personnel = incubationFactory.getPersonnel();
        if (StringUtils.isNotBlank(personnel)) {

            List<String> list = Arrays.asList(personnel.split(","));
            list = list.stream()
                    .filter(id1 -> !id1.equals(loginUser.getUserId().toString()))
                    .collect(Collectors.toList());
            incubationFactory.setPersonnel(String.join(",", list));//添加认领人转成字符串
            int i = incubationFactoryMapper.updateById(incubationFactory);

        }
        return AjaxResult.success("取消成功");
    }

    @Override
    public AjaxResult transform(String[] id, LoginUser loginUser) {
        try {
//            new Thread(() -> {
            //查询所有成果
            LambdaQueryWrapper<IncubationFactory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(IncubationFactory::getId, id);
            queryWrapper.in(IncubationFactory::getEvaluateStatus, 0, -1);//只选未评估和未通过的
            queryWrapper.eq(IncubationFactory::getDelFlag, 0);
            List<IncubationFactory> incubationFactoryList = incubationFactoryMapper.selectList(queryWrapper);

//
            //更新成果表状态
            IncubationFactory factory = new IncubationFactory();
            factory.setEvaluateStatus("2");
            factory.setConvertRate("60");
            factory.setAnalysisStatus("已完成评估（强制通过）");
            factory.setEvaluateTitle("已完成评估（强制通过）");
            int update = incubationFactoryMapper.update(factory, queryWrapper);

//            });

            return AjaxResult.success("非评估中以及通过的成果 转换成功");
        } catch (Exception e) {
            log.error("###转换失败，原因：" + e.getMessage());
            return AjaxResult.error("转换失败，请联系管理员解决");
        }
    }

    @Override
    public AjaxResult dictionary() {
        try {
            LinkedMap<String, Object> linkedMap = new LinkedMap<>();
            //研究类型
            List<Map<String, String>> research = extracted(研究类型);
            linkedMap.put("研究类型", research);
            List<Map<String, String>> subject = extracted(学科类型);
            linkedMap.put("学科类型", subject);
            List<Map<String, String>> institution = extracted(机构来源);
            linkedMap.put("机构来源", institution);
            return AjaxResult.success(linkedMap);
        } catch (Exception e) {
            log.error("###字典查询失败，原因：" + e.getMessage());
            return AjaxResult.error("字典查询失败，请联系管理员解决");
        }
    }

    @Override
    public List<Map<String, String>> getDict(String name) {
        return extracted(name);
    }

    @Override
    public AjaxResult getAllFactoryStatistics(TransferDTO dto) {
        try {
            LinkedMap<String, Object> maps = new LinkedMap<>();
            List<Map<String, String>> research = extracted(研究类型);
            List<Map<String, String>> subject = extracted(学科类型);

            //转换为条件语句
            String s = editTransfer(dto);
            if (s.equals("存在无效字段")) {
                return AjaxResult.error(s + "，请检查字段名称是否正确，再次发生请联系管理员");
            }
            //查询所有数据
            List<FactoryPageVO> incubationFactories = incubationFactoryMapper.listForTransfer(dto.getSubConditions(),
                    dto.getEndTime() == null ? null : DateUtils.dateToString(dto.getEndTime(), "yyyy-MM-dd"),
                    dto.getStartTime() == null ? null : DateUtils.dateToString(dto.getStartTime(), "yyyy-MM-dd"),
                    null, ValueIsNull(dto.getSubConditions()), null);
            //数据整理
            Map<String, List<IncubationFactory>> groupedByResearchType = incubationFactories.stream()
                    .collect(Collectors.groupingBy(factory ->
                            StringUtils.isBlank(factory.getResearchType()) ? "other" : factory.getResearchType()));
            Map<String, List<IncubationFactory>> groupedBySubjectType = incubationFactories.stream()
                    .collect(Collectors.groupingBy(factory ->
                            StringUtils.isBlank(factory.getSubjectType()) ? "other" : factory.getSubjectType()));
            Map<String, List<IncubationFactory>> groupedByInstitution = incubationFactories.stream()
                    .collect(Collectors.groupingBy(factory ->
                            StringUtils.isBlank(factory.getInstitution()) ? "其他" : factory.getInstitution()));
            research.forEach(item -> {
                List<IncubationFactory> incubationFactories1 = groupedByResearchType.get(item.get("value"));
                item.put("count", String.valueOf(incubationFactories1 == null ? 0 : incubationFactories1.size()));
            });
            subject.forEach(item -> {
                List<IncubationFactory> incubationFactories1 = groupedBySubjectType.get(item.get("value"));
                item.put("count", String.valueOf(incubationFactories1 == null ? 0 : incubationFactories1.size()));
            });

            List<Map<String, String>> institution = new LinkedList<>();
            groupedByInstitution.forEach((k, v) -> {
                LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();
                hashMap.put("key", k);
                hashMap.put("value", k);
                hashMap.put("count", String.valueOf(v.size()));
                institution.add(hashMap);
            });
            List<Map<String, String>> transformation = new ArrayList<>();

            LinkedHashMap<String, String> waitingMap = new LinkedHashMap<>();
            waitingMap.put("key", "待认领，未转化");
            waitingMap.put("value", "waiting");
            waitingMap.put("count", "0");

            LinkedHashMap<String, String> operationMap = new LinkedHashMap<>();
            operationMap.put("key", "已认领，转化中");
            operationMap.put("value", "operation");
            operationMap.put("count", "0");

            // 将默认项添加到 transformation 列表中
            transformation.add(waitingMap);
            transformation.add(operationMap);

            // 处理分组统计
            Map<String, List<IncubationFactory>> isCompleteT = incubationFactories.stream()
                    .filter(factory -> !"1".equals(factory.getIsComplete())) // 添加过滤条件，排除 isComplete=1 的数据
                    .collect(Collectors.groupingBy(factory -> {
                        // 解析 personnel 并计算数量
                        int personnelCount = 0;
                        if (StringUtils.isNotBlank(factory.getPersonnel())) {
                            personnelCount = factory.getPersonnel().split(",").length;
                        }

                        // 根据 personnel 数量与 personNum 的关系进行分组
                        Integer personNum = factory.getPersonNum();

                        if (personnelCount < personNum) {
                            return "waiting"; // 未满员
                        } else {
                            return "operation"; // 满员
                        }
                    }));

            // 更新对应项的计数
            isCompleteT.forEach((k, v) -> {
                transformation.stream()
                        .filter(item -> k.equals(item.get("value")))
                        .findFirst()
                        .ifPresent(item -> item.put("count", String.valueOf(v.size())));
            });

            maps.put("转化状态", transformation);
            maps.put("研究类型", research);
            maps.put("机构来源", institution);
            maps.put("学科类型", subject);
            return AjaxResult.success(maps);
        } catch (Exception e) {
            log.error("统计失败：" + e.getMessage());
            return AjaxResult.error("左侧筛选统计失败，请联系管理员解决");
        }
    }

    @Override
    public AjaxResult listForConditions() {
        try {
            List<MapVO> conditions = incubationFactoryMapper.getConditions();
            return AjaxResult.success(conditions);
        } catch (Exception e) {
            log.error("###条件选择列表失败，原因：" + e.getMessage());
            return AjaxResult.error("条件选择列表失败，请联系管理员解决");
        }
    }

    @Override
    public TableDataInfo listForTransfer(TransferDTO dto, LoginUser proUser) {
        try {
            //做字段筛选
            String s = editTransfer(dto);
            if (s.equals("存在无效字段")) {
                return OtherUtil.tableError(s + "，请检查字段名称是否正确");
            }
            final Integer[] isCompleteT = {0};
            //Todo 左侧条件筛选暂时去掉转化状态，确定怎么调整之后在去掉
            Map<String, List<String>> map = new LinkedMap<>();
            if (dto.getType() != null && dto.getType().size() > 0) {
                dto.getType().forEach((key, value) -> {
                    if (!key.equals("转化状态")) {
                        String name = "";
                        List<String> strings = dto.getType().get(key);
                        switch (key) {
                            case "研究类型":
                                name = 研究类型;
                                break;
                            case "学科类型":
                                name = 学科类型;
                                break;
                            case "机构来源":
                                name = 机构来源;
                                break;
                            default:
                                break;
                        }
                        if (StringUtils.isNotBlank(name)) {
                            map.put(name, strings);
                        }
                    } else {
                        isCompleteT[0] = value.get(0).equals("waiting") ? 1 : 2;
                    }

                });
            }
            //分页查询
            startPage(dto.getPageDomain());
            List<FactoryPageVO> factoryPageVOS = incubationFactoryMapper.listForTransfer(dto.getSubConditions(),
                    dto.getEndTime() == null ? null : DateUtils.dateToString(dto.getEndTime(), "yyyy-MM-dd"),
                    dto.getStartTime() == null ? null : DateUtils.dateToString(dto.getStartTime(), "yyyy-MM-dd"),
                    map,
                    ValueIsNull(dto.getSubConditions()),
                    isCompleteT[0]);
            //取当前页成果的文件
            List<String> fileIds = factoryPageVOS.stream().map(FactoryPageVO::getId).collect(Collectors.toList());

            LambdaQueryWrapper<IncubationFile> wrapper = new LambdaQueryWrapper<>();
            if (CollectionUtils.isNotEmpty(fileIds)) {
                wrapper.in(IncubationFile::getIncuId, fileIds);
            }
            List<IncubationFile> incubationFiles = incubationFileMapper.selectList(wrapper);
            Map<String, List<IncubationFile>> fileForFactory = incubationFiles.stream()
                    .collect(Collectors.groupingBy(IncubationFile::getIncuId));
            LinkedList<Map<String, Object>> maps = new LinkedList<>();
            //获取研究类型
            List<Map<String, String>> research = extracted(研究类型);
            List<Map<String, String>> institution = extracted(机构来源);
            //后续操作，返回列表补充字段
            factoryPageVOS.forEach(factoryPageVO -> {
                Map<String, Object> map1 = new LinkedMap<>();
                map1.put("id", factoryPageVO.getId());
                map1.put("name", factoryPageVO.getName());//成果名称
                map1.put("author", factoryPageVO.getAuthor());// 作者
//                map1.put("institution", factoryPageVO.getInstitution());
                // 机构来源--对应作者后面
//                if (StringUtils.isNotBlank(factoryPageVO.getInstitution())) {
//                    String researchType = institution.stream()
//                            .filter(item -> factoryPageVO.getInstitution().equals(item.get("value")))
//                            .map(item -> item.get("key"))
//                            .findFirst()
//                            .orElse("其他");
                    map1.put("institution", factoryPageVO.getInstitution());
//                } else {
//                    map1.put("institution", "其他");    //研究类型
//                }
                map1.put("journalName", factoryPageVO.getJournalName());//期刊名称
                map1.put("createTime", DateUtils.dateToString(factoryPageVO.getCreateTime(), "yyyy-MM-dd"));//创建时间
                map1.put("title", OtherUtil.extractFirstHtml(factoryPageVO.getTitle()));// 摘要
                map1.put("label", factoryPageVO.getLabel());//关键词
                map1.put("source", factoryPageVO.getSource());// 来源

                //***研究类型
                if (StringUtils.isNotBlank(factoryPageVO.getResearchType())) {
                    String researchType = research.stream()
                            .filter(item -> factoryPageVO.getResearchType().equals(item.get("value")))
                            .map(item -> item.get("key"))
                            .findFirst()
                            .orElse("其他");
                    map1.put("researchType", researchType);
                } else {
                    map1.put("researchType", "其他");    //研究类型
                }

                map1.put("convertRate", factoryPageVO.getConvertRate());//转化率

                //***文件数据
                LinkedMap<String, Boolean> fileData = new LinkedMap<>();
                List<IncubationFile> incubationFiles1 = fileForFactory.get(factoryPageVO.getId());
                if (CollectionUtils.isNotEmpty(incubationFiles1)) {
                    Map<String, List<IncubationFile>> collect = incubationFiles1.stream()
                            .collect(Collectors.groupingBy(IncubationFile::getFileType));
                    fileData.put("成果全文", collect.containsKey(文献));
                    fileData.put("数据", collect.containsKey(数据));
                    fileData.put("代码", collect.containsKey(代码));
                    fileData.put("其他", collect.containsKey(其他));
                } else {
                    fileData.put("成果全文", false);
                    fileData.put("数据", false);
                    fileData.put("代码", false);
                    fileData.put("其他", false);
                }
                map1.put("fileData", fileData);//文件数据存在与否

                //***认领状态
                String personnel = factoryPageVO.getPersonnel();
                String userId = proUser != null && proUser.getUserId() != null ? proUser.getUserId().toString() : null;
                Integer isClaim = 0;
                Integer personnelNum = 0;
                Integer personNum = factoryPageVO.getPersonNum();
                if (StringUtils.isNotBlank(personnel) && userId != null) {
                    Set<String> personnelSet = new HashSet<>(Arrays.asList(personnel.split(",")));
                    personnelNum = personnelSet.size();
                    isClaim = personnelSet.contains(userId) ? 1 : 0;
                    if (isClaim == 0) {
                        isClaim = personNum - personnelNum == 0 ? -1 : isClaim;
                    }
                }
                /**********/
                map1.put("isClaim", isClaim);//成果认领状态(0未认领，1已认领,-1无法认领)
                map1.put("personnelNum", personnelNum + "/" + factoryPageVO.getPersonNum());//成果认领人数比


                maps.add(map1);
            });


            return OtherUtil.tableSuccess2(maps, new PageInfo(factoryPageVOS).getTotal());
        } catch (Exception e) {
            log.error("###项目列表查询失败，原因：" + e.getMessage());
            return OtherUtil.tableError("项目列表查询失败，请联系管理员解决");
        }
    }

    @Override
    public AjaxResult claimDelList(String[] ids, LoginUser loginUser) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Project::getId, ids)
                .eq(Project::getDelFlag, 0);
        boolean isUnauthorizedRole = loginUser.getUser().getRoles().stream()
                .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId() != 2L);
        //判断权限，仅管理员和机构管理员可以直接取消
        if (!isUnauthorizedRole) {
            queryWrapper.eq(Project::getCreateUser, loginUser.getUserId().toString());
        }
        //找出认领的成果
        List<Project> projectList = projectMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(projectList) && projectList.size() == 0) {
            return AjaxResult.error("取消失败，请检查该成果是否认领");
        }
        projectList.forEach(project -> {
            if (isUnauthorizedRole) {
                queryWrapper.eq(Project::getCreateUser, project.getCreateUser());
                loginUser.setUserId(Long.valueOf(project.getCreateUser()));
            }
            project.setDelFlag("2");
        });
//        int update = projectMapper.update(project, queryWrapper);
        boolean b = projectService.saveOrUpdateBatch(projectList);


        //先查看当前成果是否存在 incubation_factory
        CompletableFuture.runAsync(() -> {
            projectList.forEach(project -> {
                LambdaQueryWrapper<IncubationFactory> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(IncubationFactory::getId, project.getIncuId())
                        .eq(IncubationFactory::getEvaluateStatus, 2);//已通过
                IncubationFactory incubationFactory = incubationFactoryMapper.selectOne(wrapper);
                if (incubationFactory != null) {
                    //看成果认领情况
                    String personnel = incubationFactory.getPersonnel();
                    if (StringUtils.isNotBlank(personnel)) {

                        List<String> list = Arrays.asList(personnel.split(","));
                        list = list.stream()
                                .filter(id1 -> !id1.equals(loginUser.getUserId().toString()))
                                .collect(Collectors.toList());
                        incubationFactory.setPersonnel(String.join(",", list));//添加认领人转成字符串
                        int i = incubationFactoryMapper.updateById(incubationFactory);

                    }
                }
            });
        });
        return AjaxResult.success("取消成功");
    }

    @Override
    public List<String> selectAssess(List<String> incubationList) {
        //找出所有未通过和未审核的成果
        LambdaQueryWrapper<IncubationFactory> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(IncubationFactory::getId, incubationList)
                        .in(IncubationFactory::getEvaluateStatus, "0", "-1")
                .eq(IncubationFactory::getDelFlag, 0);
        List<IncubationFactory> incubationFactories = incubationFactoryMapper.selectList(wrapper);

        //找出所有成果的id
        List<String> collect =  incubationFactories.stream().map(IncubationFactory::getId)
                .collect(Collectors.toList());
        //找出成果下存在文件的活动
        if (CollectionUtil.isNotEmpty(collect)) {
            LambdaQueryWrapper<IncubationFile> fileWrapper = new LambdaQueryWrapper<>();
            fileWrapper.in(IncubationFile::getIncuId, collect)
                    .eq(IncubationFile::getDelFlag, "0")
                    .eq(IncubationFile::getFileType, "1");
            List<IncubationFile> incubationFiles = incubationFileService.list(fileWrapper);
            //找出所有有文件的成果id
            collect =  incubationFiles.stream()
                    .map(IncubationFile::getIncuId)
                    .distinct()
                    .collect(Collectors.toList());
        }
        return collect;


    }

    @Override
    public void editList(List<String> incubationFactories) {
        List<IncubationFactory> incubationFactories1 = new ArrayList<>();
        incubationFactories.forEach(incubationFactory -> {
            IncubationFactory factory = new IncubationFactory();
            factory.setId(incubationFactory);
            factory.setParsingStatus("1");
            factory.setAnalysisStatus("成果解析中");
            incubationFactories1.add( factory);
        });
        boolean b = updateBatchById(incubationFactories1);
        if (!b) {
            log.error("修改失败,数据库修改状态错误，错误内容有：\n"+incubationFactories1);
            throw new ServiceException("修改失败,请联系管理员", HttpStatus.BAD_REQUEST);
        }
    }

    @Override
    public List<String> selectExtract(List<String> incubationList) {
        //找出所有未通过和未审核的成果
        LambdaQueryWrapper<IncubationFactory> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(IncubationFactory::getId, incubationList)
                .in(IncubationFactory::getParsingStatus, "0", "-1")
                .eq(IncubationFactory::getEvaluateStatus,"2" )
                .eq(IncubationFactory::getDelFlag, 0);
        List<IncubationFactory> incubationFactories = incubationFactoryMapper.selectList(wrapper);

        //找出所有成果的id
        List<String> collect =  incubationFactories.stream().map(IncubationFactory::getId)
                .collect(Collectors.toList());
        //找出成果下存在文件的活动
        if (CollectionUtil.isNotEmpty(collect)) {
            LambdaQueryWrapper<IncubationFile> fileWrapper = new LambdaQueryWrapper<>();
            fileWrapper.in(IncubationFile::getIncuId, collect)
                    .eq(IncubationFile::getDelFlag, "0")
                    .eq(IncubationFile::getFileType, "1");
            List<IncubationFile> incubationFiles = incubationFileService.list(fileWrapper);
            //找出所有有文件的成果id
            collect =  incubationFiles.stream().map(IncubationFile::getIncuId)
                    .collect(Collectors.toList());
        }
        return collect;
    }

    @Override
    public AjaxResult editIncuPro(String incubationId) {
        //查询所有成果
        LambdaQueryWrapper<IncubationFactory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(IncubationFactory::getId, incubationId);
        queryWrapper.eq(IncubationFactory::getEvaluateStatus, 2);//评估通过
        queryWrapper.eq(IncubationFactory::getParsingStatus, 2);//解析通过
        queryWrapper.eq(IncubationFactory::getDelFlag, 0);
        List<IncubationFactory> incubationFactoryList = incubationFactoryMapper.selectList(queryWrapper);
//        System.out.println("incubationFactoryList = " + incubationFactoryList);
        //插入项目中间表
        incubationFactoryList.forEach(incubationFactory -> {
            IncubationProject project = new IncubationProject();
            project.setId(getId());// id
            project.setIncuId(incubationFactory.getId());// 成果id
            project.setProName(incubationFactory.getName());// 成果名
            project.setAuthor(incubationFactory.getAuthor());// 作者名
            project.setTitle(incubationFactory.getTitle());// 简介/特色
            project.setChargePerson(incubationFactory.getSource());//主办方
            project.setCorrespAuthor(incubationFactory.getCorrespAuthor());//通讯作者
            project.setCorrespEmail(incubationFactory.getCorrespEmail());//通讯邮箱
            project.setIsRange("1");//可见状态
            project.setStatus("1");//状态
            project.setBanner("");//头图地址
            project.setUrl("");//图片地址
            int insert = incubationProjectMapper.insert(project);
        });
        return AjaxResult.success("添加成功");
    }

    private Boolean ValueIsNull(List<SearchConditionDto> subConditions) {
        if (CollectionUtils.isEmpty(subConditions)) {
            return true;
        } else {
            for (SearchConditionDto subCondition : subConditions) {
                if (StringUtils.isNotBlank(subCondition.getValue())) {
                    return false;
                }
            }
        }
        return true;
    }


    private String editTransfer(TransferDTO dto) {
        List<MapVO> conditions = incubationFactoryMapper.getConditions();
        Set<String> validFields = conditions.stream()
                .map(mapVO -> (String) mapVO.getValue())
                .collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(dto.getSubConditions())) {
            for (SearchConditionDto subCondition : dto.getSubConditions()) {
                if (!validFields.contains(subCondition.getName())) {
                    return "存在无效字段";
                }
            }
        }
        return "";
    }

    private List<Map<String, String>> extracted(String name) {
        LinkedList<Map<String, String>> maps = new LinkedList<>();
        SysDictData dictData = new SysDictData();
        dictData.setDictType(name);
        List<SysDictData> sysDictData = dictDataMapper.selectDictDataList(dictData);
        sysDictData.forEach(item -> {
            LinkedMap<String, String> linkedMap = new LinkedMap<>();
            linkedMap.put("key", item.getDictLabel());
            linkedMap.put("value", item.getDictValue());
            maps.add(linkedMap);
        });
        return maps;
    }

    private List<FactoryPageVO> IncubationClaimList(FactoryPageDTO dto, ArrayList<String> list, LoginUser proUser) {
        startPage(dto.getPageDomain());
        List<FactoryPageVO> factoryPageVOS = incubationFactoryMapper.selectClaimList(dto, list);
//        Map<String, List<FactoryPageVO>> groupedById = factoryPageVOS.stream()
//                .collect(Collectors.groupingBy(FactoryPageVO::getId));
//        List<FactoryPageVO> result = new ArrayList<>();
//        for (Map.Entry<String, List<FactoryPageVO>> entry : groupedById.entrySet()) {
//            List<FactoryPageVO> group = entry.getValue();
//            // 查找projectUser和proUser.getUserId()相同的记录
//            Optional<FactoryPageVO> matched = group.stream()
//                    .filter(vo -> vo.getProjectUser() != null &&
//                            vo.getProjectUser().equals(proUser.getUserId()))
//                    .findFirst();
//
//            // 如果找到匹配的则添加匹配的，否则添加第一条
//            result.add(matched.orElse(group.get(0)));
//        }

        return factoryPageVOS;

//        List<FactoryPageVO> factoryPageVOS = incubationFactoryMapper.selectListForUser(dto);
//        return factoryPageVOS;
    }

    private List<FactoryPageVO> otherForClaim(FactoryPageDTO dto, LoginUser proUser) {
        List<FactoryPageVO> factoryPageVOS = incubationFactoryMapper.otherForClaim(dto, proUser.getUserId());
        return factoryPageVOS;
    }

    private List<FactoryPageVO> IncubationSearch(FactoryPageDTO dto) {
        startPage(dto.getPageDomain());
        List<FactoryPageVO> incubationFactories = incubationFactoryMapper.selectListForUser(dto);
        return incubationFactories;
    }

    /**
     * 文件转换
     *
     * @param projectFiles
     * @return
     */
    private List<ProjectIndexFileDTO> fileToVo(List<IncubationFile> projectFiles) {
        ArrayList<ProjectIndexFileDTO> indexFileDTOList = new ArrayList<>();
        for (IncubationFile projectFile : projectFiles) {
            ProjectIndexFileDTO indexFileDTO = new ProjectIndexFileDTO();
            BeanUtils.copyProperties(projectFile, indexFileDTO);
            indexFileDTO.setProId(projectFile.getIncuId());
            String url = indexFileDTO.getUrl().startsWith("/") ? indexFileDTO.getUrl() : "/" + indexFileDTO.getUrl();
//            indexFileDTO.setFullurl(sysUrl + "/prod-api" + url);
            indexFileDTO.setFullurl(UrlUtils.getUrl() + url);
            indexFileDTOList.add(indexFileDTO);
        }
        return indexFileDTOList;
    }

    /**
     * 通用文件查询内容
     *
     * @param strings
     * @return
     */
    private Map<String, List<IncubationFile>> infoFileList(ArrayList<String> strings) {
        LambdaQueryWrapper<IncubationFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(IncubationFile::getIncuId, strings)
                .eq(IncubationFile::getDelFlag, "0");
        List<IncubationFile> incubationFiles = incubationFileMapper.selectList(wrapper);
        //按照成果id进行分组（包含有所有文件）
        return incubationFiles.stream()
                .collect(Collectors.groupingBy(IncubationFile::getIncuId));
    }

    private String dataEdit(IncubationFactory incubationFactory, String userId) {
        try {
            if (StringUtils.isBlank(incubationFactory.getId())) {
                incubationFactory.setId(getId());
                incubationFactory.setCreateUser(String.valueOf(userId));
//                incubationFactory.setSource("平台上传");
                int i = incubationFactoryMapper.insert(incubationFactory);
                if (i == 0) {
                    return "";
                }
            } else {
                incubationFactory.setUpdateUser(String.valueOf(userId));
                int i = incubationFactoryMapper.updateById(incubationFactory);
                if (i == 0) {
                    return "";
                }
            }
            return incubationFactory.getId();
        } catch (Exception e) {
            log.error("==成果字段保存失败：", e);
            return "";
        }
    }


    private Boolean fileEdit(IncubationFactoryDTO dto, LoginUser loginUser) {
        if (dto.getFileList() != null && !dto.getFileList().isEmpty()) {
            for (IncubationFileDTO fileDTO : dto.getFileList()) {
                IncubationFile incubationFile = new IncubationFile();
                if (fileDTO.getIsDel() == true) {
                    incubationFile.setId(fileDTO.getId());
                    incubationFile.setDelFlag("2");
                    incubationFileMapper.updateById(incubationFile);
                } else {
                    if (StringUtils.isBlank(fileDTO.getId())) {
                        BeanUtils.copyProperties(fileDTO, incubationFile);
                        if (StringUtils.isBlank(incubationFile.getIncuId())) {
                            incubationFile.setIncuId(dto.getId());
                        }
                        incubationFile.setCreateUser(String.valueOf(loginUser.getUserId()));
                        incubationFile.setId(getId());
                        incubationFileMapper.insert(incubationFile);
                    }
                }
            }
        }
        return true;
    }


    @Override
    public TableDataInfo listForPageIncubation(FactoryPageDTO dto, LoginUser proUser) {
        //  todo 还没对的，记得需要看下怎么做权限

        //成果搜索
//        List<FactoryPageVO> factories = IncubationSearch(dto);
        List<FactoryPageVO> factories = IncubationClaimList(dto, null,proUser);
        if (factories.isEmpty()) {
            return OtherUtil.tableSuccess2(factories, 0L);
        }

        // 批量查询所有成果对应的文件信息，提高性能
        List<String> factoryIds = factories.stream()
                .map(FactoryPageVO::getId)
                .collect(Collectors.toList());

        LambdaQueryWrapper<IncubationFile> fileWrapper = new LambdaQueryWrapper<>();
        fileWrapper.in(IncubationFile::getIncuId, factoryIds)
                .eq(IncubationFile::getDelFlag, "0");
        List<IncubationFile> allFiles = incubationFileMapper.selectList(fileWrapper);

        // 按incuId分组文件
        Map<String, List<IncubationFile>> filesByFactoryId = allFiles.stream()
                .collect(Collectors.groupingBy(IncubationFile::getIncuId));

        // 为每个成果添加文件类型信息和认领状态
        for (FactoryPageVO factory : factories) {
            List<IncubationFile> files = filesByFactoryId.getOrDefault(factory.getId(), new ArrayList<>());

            // 构建材料完整性字符串
            LinkedMap<String, Boolean> fileData = new LinkedMap<>();
            fileData.put("成果全文", false);
            fileData.put("数据", false);
            fileData.put("代码", false);
            fileData.put("环境", false);
            for (IncubationFile file : files) {
                String fileType = file.getFileType();
                switch (fileType) {
                    case "1":
                        fileData.put("成果全文", true);
                        break;
                    case "2":
                        fileData.put("数据", true);
                        break;
                    case "3":
                        fileData.put("代码", true);
                        break;
                    case "4":
                        fileData.put("环境", true);
                        break;
                    default:
                        // 其他类型不处理
                        break;
                }
            }

            // 用顿号拼接材料完整性
            factory.setMaterialCompleteness(fileData);

            // 构建认领状态字符串 "personNum/5"
            Integer personNum = factory.getPersonNum();
            String personnel = factory.getPersonnel();
            if (personNum == null) {
                continue;
            }
            int personnelCount = 0;
            if (personnel != null && !personnel.trim().isEmpty()) {
                String[] parts = personnel.split(",");
                for (String part : parts) {
                    if (part != null && !part.trim().isEmpty()) {
                        personnelCount++;
                    }
                }
            }
            factory.setClaimStatus(personnelCount + "/" + personNum);
        }

        return OtherUtil.tableSuccess2(factories, new PageInfo(factories).getTotal());
    }

    /**
     * 查询表里全部数据并返回统计数据
     *
     * @return 包含统计数据的JSON对象
     */
    @Override
    public Map<String, Object> getAllIncubationFactoriesStatistics(LoginUser loginUser) {
        //  todo 还没对的，记得需要看下怎么做权限

        LambdaQueryWrapper<IncubationFactory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IncubationFactory::getDelFlag, "0");
        List<IncubationFactory> allFactories = incubationFactoryMapper.selectList(wrapper);

        // 统计evaluateStatus等于2的数据数量（已通过）
        long convertedIntoResults = allFactories.stream()
                .filter(factory -> "2".equals(factory.getEvaluateStatus()))
                .filter(factory -> "2".equals(factory.getParsingStatus()))
                .filter(factory -> !("1".equals(factory.getIsComplete())))
                .count();

        // 统计evaluateStatus等于1的数据数量（评估中）
        /*long transformationResults = allFactories.stream()
                .filter(factory -> "1".equals(factory.getEvaluateStatus()))
                .count();*/

        long transformationResults = 0l;
        for (IncubationFactory factory : allFactories) {
            Integer personNum = factory.getPersonNum();
            String personnel = factory.getPersonnel();
            if (personNum == null) {
                continue;
            }
            int personnelCount = 0;
            if (personnel != null && !personnel.trim().isEmpty()) {
                String[] parts = personnel.split(",");
                for (String part : parts) {
                    if (part != null && !part.trim().isEmpty()) {
                        personnelCount++;
                    }
                }
            }
            if (personnelCount == personNum) {
                transformationResults++;
            }
        }

        long unclaimedResults = transformationResults > 0 && convertedIntoResults > 0
                ? convertedIntoResults - transformationResults
                : convertedIntoResults;

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("convertedIntoResults", convertedIntoResults);
        result.put("transformationResults", transformationResults);
        result.put("unclaimedResults", unclaimedResults);

        return result;
    }


}
